<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use Hyperf\HttpMessage\Stream\SwooleStream;
use \Hyperf\HttpServer\CoreMiddleware as BaseCoreMiddleware;
use Psr\Http\Message\ServerRequestInterface;

class CoreMiddleware extends BaseCoreMiddleware {
    /**
     * Handle the response when cannot found any routes.
     */
    protected function handleNotFound(ServerRequestInterface $request): mixed {
        return $this->buildResponse([
            'code' => ErrorCode::INVALID,
            'msg'  => '接口地址异常',
            'data' => []
        ]);
    }

    /**
     * Handle the response when the routes found but doesn't match any available methods.
     */
    protected function handleMethodNotAllowed(array $methods, ServerRequestInterface $request): mixed {
        if ($request->getMethod() === 'OPTIONS') {
            return $this->buildResponse([
                'code' => ErrorCode::SUCCESS,
                'msg'  => ErrorCode::getMessage(ErrorCode::SUCCESS),
                'data' => []
            ]);
        }

        return $this->buildResponse([
            'code' => ErrorCode::INVALID,
            'msg'  => '接口地址异常',
            'data' => []
        ]);
    }

    /**
     * 构建返回参数
     * @param $data
     * @return mixed
     */
    private function buildResponse($data): mixed {
        return $this->response()->withStatus(200)
            ->withHeader('Content-Type', 'application/json')
            ->withBody(new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE)));
    }
}
